/*
 * @Description: 头部拦截器
 * @Author: iamsmiling
 * @Date: 2021-05-25 11:27:58
 * @LastEditTime: 2021-06-16 06:59:35
 */

// 必须是顶层函数
import 'dart:convert';

import 'package:credit_business_circle/http_kit/interceptor/http_error_interceptor.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

import 'exception/base_http_exception.dart';
import 'interceptor/header_interceptor.dart';
import 'interceptor/token_interceptor.dart';
import 'interceptor/log_interceptor.dart' as logger;

_parseData(String response) {
  return jsonDecode(response);
}

parseJson(String text) {
  return compute(_parseData, text);
}

class HttpKit {
  static HttpKit _singleton = HttpKit._();

  factory HttpKit() => _singleton;

  late Dio dio;

  HttpKit._() {
    dio = Dio();

    dio.options = BaseOptions(baseUrl: "");

    ///在isolate中进行数据解析
    (dio.transformer as DefaultTransformer).jsonDecodeCallback = parseJson;

    ///为每个请求添加头部
    dio.interceptors.add(HeaderInterceptor());

    ///为每个请求添加token
    dio.interceptors.add(TokenInterceptor());

    ///错误拦截
    dio.interceptors.add(HttpErrorInterceptor());

    ///打印
    dio.interceptors.add(logger.LogInterceptor());

    ///...自定义拦截器 做业务逻辑处理
  }

  ///封装get方法
  Future get(String url, {Map? params, Options? options}) async {
    return dio
        .get(url,
            queryParameters: params?.cast<String, dynamic>(), options: options)
        .then((Response response) {
      return response.data;
    }, onError: (err) {
      // setError(err);
      throw err;
    });
  }

  ///封装post方法
  Future post(String url,
      {Map? params,
      Options? options,
      dynamic formData,
      Interceptor? interceptor}) async {
    return dio
        .post(url,
            queryParameters: params?.cast<String, dynamic>(),
            data: formData is Map ? formData.cast<String, dynamic>() : formData,
            options: options)
        .then((Response response) {
      return response.data;
    }, onError: (err) {
      setError(err);
      throw err;
    });
  }

  /// [e]分类Error和Exception两种
  void setError(e, {String? message}) {
    if (e is BaseHttpException) {
      print(e.message);
      e.onException();
    }
    // if (e is DioError) {
    //   ToastKit.error("连接失败");
    // }
  }
}
